from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, ListModelMixin
from rest_framework.generics import GenericAPIView, UpdateAPIView
from rest_framework.decorators import action
from apps.models import User, HouseKeeping
from apps.serializers.ListHousekeeping import ListThingSerializer
from apps.serializers.UserSerializer import UserSerializer, LoginLogSerializer, LoginSerializer, UserUpdateSerializer
from apps.serializers.ListHousekeeping import ListThingSerializer
from apps.serializers.UpdateSerializer import UpdateDataSerializer
from apps.serializers.Order import OrderSerializer
from apps.utils.common_function import md5value, get_ip, get_ua
from apps.utils.common_mixin import APICreateModelMixin
from apps.utils.common_response import APIResponse
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.hashers import make_password, check_password
from rest_framework import status


from rest_framework.viewsets import GenericViewSet
from apps.models import HouseKeeping, Order


class UserRegister(GenericViewSet):
    serializer_class = UserSerializer
    authentication_classes = []
    permission_classes = []

    def create(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return APIResponse(msg="注册成功！")
        return APIResponse(code=1, msg="注册失败, 用户名至少2位,密码至少6位。")


def make_login_log(request, *args, **kwargs):
    try:
        username = request.data['username']
        data = {

            "username": username,
            "ip": get_ip(request),
            "ua": get_ua(request)
        }
        serializer = LoginLogSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
    except Exception as e:
        print(e)

class LoginView(GenericViewSet):
    serializer_class = LoginSerializer
    authentication_classes = []
    permission_classes = []
    
    def create(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        id= serializer.context.get('user_id')
        cover=User.objects.filter(id=id).first().cover
        # print(cover)
        data = {
            "username": serializer.context.get('username'),
            "user_id": serializer.context.get('user_id'),
            "token": serializer.context.get('token'),
            "cover":'/media/'+str(cover)
        }
        return APIResponse(msg="登录成功！", data=data)

class CreateView(GenericViewSet,APICreateModelMixin):
    queryset = HouseKeeping.objects.all()
    serializer_class = ListThingSerializer


    
# 返回登录的单个用户的接口
class GetUserDataView(GenericViewSet, RetrieveModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
    
    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

class ListUserSetting(GenericViewSet):
    def list(self, request):
        try:
            id = request.GET.get('id')
            user_data = User.objects.filter(id=id).first()
        except User.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        serializer = UserUpdateSerializer(user_data)
        return APIResponse(code=0, msg='更新成功', data=serializer.data)
#个人设置
class UpdateData(GenericViewSet):
    def create(self, request):
        try:
            id = request.GET.get('id')
            user_data = User.objects.filter(id=id).first()
        except User.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        serializer = UserUpdateSerializer(user_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
        return APIResponse(code=0, msg='更新成功', data=serializer.data)

    
    

# http://127.0.0.1:8000/api/v1/order/
class OrderView(ViewSet, GenericAPIView, ListModelMixin):
    """家政订单接口（我的预约）"""
    
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    
    @action(methods=['GET'], detail=False)
    def order(self, request, *args, **kwargs):
        order_instance = self.get_queryset()
        serializer = self.get_serializer(instance=order_instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        return APIResponse(data=serializer.data)


class ChangePasswordView(APIView):
    def post(self, request, *args, **kwargs):

        old_password = request.data.get('oldPassword')
        new_password = request.data.get('newPassword')
        re_password = request.data.get('rePassword')
        user_id = request.data.get('id')
        user = User.objects.get(id=user_id)
        if new_password == re_password:
            tag = check_password(old_password, user.password)
            if tag:
                user.password = make_password(new_password)
                user.save()
                return APIResponse(msg='密码修改成功')
            return APIResponse(msg='两次输入的密码不一致', status=status.HTTP_400_BAD_REQUEST)
        return APIResponse(code=1, msg='新密码与旧密码一致', status=status.HTTP_400_BAD_REQUEST)


class Logout(GenericViewSet):
    def create(self, request):
        try:
            id = request.GET.get('id')
            # 批量删除
            User.objects.filter(id=id).delete()
        except User.DoesNotExist:
            make_login_log(request)
            return APIResponse(code=1, msg='对象不存在')
        return APIResponse(code=0, msg='删除成功')
